<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Operators</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, operators, programming, language, learn Python">
<meta name="description" content="In this part of the Python tutorial, we 
work with operators.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Operators</h1>

<p>
In this part of the Python programming tutorial, we will talk about operators. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
An <b>operator</b> is a special symbol which indicates a certain 
process is carried out. Operators in programming languages are taken from mathematics.
Programmers work with data. The operators are used to process data. 
</p>

<p>
In Python programming language, we have several types of operators:
</p>

<ul>
<li>Arithmetic operators</li>
<li>Boolean operators</li>
<li>Relational operators</li>
<li>Bitwise operators</li>
</ul>

<p>
An operator may have one or two operands. An <b>operand</b> is 
one of the inputs (arguments) of an operator. Those operators that work with only 
one operand are called <b>unary operators</b>. Those who work with two operands 
are called binary operators. 
</p>

<p>
+ and - signs can be addition and substraction operators as well as unary sign 
operators. It depends on the situation.
</p>

<pre class="code">
>>> 2
2
>>> +2
2
>>> 
</pre>

<p>
The plus sign can be used to indicate that we have a positive nubmer. But it is mostly 
not used. The minus sign changes the sign of a value.  
</p>

<pre>
>>> a = 1
>>> -a
-1
>>> -(-a)
1
</pre>

<p>
Multiplication and addition operators are examples of binary operators. They are used 
with two operands.  
</p>

<pre>
>>> 3 * 3
9
>>> 3 + 3
6
</pre>


<h2>The assignment operator</h2>


<p>
The assignment operator <b>=</b> assigns a value to a variable. In mathematics, the 
<b>=</b> operator has a different meaning. In an equation, the <b>=</b> operator is 
an equality operator. The left side of the equation is equal to the right one. 
</p>

<pre>
>>> x = 1
>>> x
1
</pre>

<p>
Here we assign a number to an x variable. 
</p>

<pre>
>>> x = x + 1
>>> x
2
</pre>

<p>
The previous expression does not make sense in mathematics. But it is legal in 
programming. The expression means that we add 1 to the x variable. The right side 
is equal to 2 and 2 is assigned to x. 
</p>

<pre>
>>> a = b = c = 4
>>> print a, b, c
4 4 4
</pre>

<p>
It is possible to assign a value to multiple variables. 
</p>

<pre>
>>> 3 = y
  File "&lt;stdin&gt;", line 1
SyntaxError: can't assign to literal
</pre>

<p>
This code example results in syntax error. We cannot assign a value to a literal. 
</p>

<h2>Arithmetic operators</h2>

<p>
The following is a table of arithmentic operators in Python programming language. 
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>+</td><td>Addition</td></tr>
<tr class="gray"><td>-</td><td>Subtraction</td></tr>
<tr><td>*</td><td>Multiplication</td></tr>
<tr class="gray"><td>/</td><td>Division</td></tr>
<tr><td>//</td><td>Floor division</td></tr>
<tr class="gray"><td>%</td><td>Modulo</td></tr>
<tr><td>**</td><td>Power</td></tr>
</table>


<p>
The following example shows arithmetic operations.
</p>

<pre class="code">
#!/usr/bin/python

# arithmetic.py

a = 10
b = 11
c = 12

add = a + b + c
sub = c - a
mult = a * b
div = c / 3

pow = a ** 2

print add, sub, mult, div
print pow
</pre>

<p>
All these are known operators from mathematics. 
</p>

<pre>
$ ./arithmetic.py 
33 2 110 4
100
</pre>

<p>
The division operations in Python may be surprising for beginners. It is 
because by default, the division operator / performs integer division. This 
means that we get an integer as a result. If we want to get a more exact 
result, we use at least one floating point number as an operand. 
</p>

<pre class="code">
#!/usr/bin/python

# division.py

print 9 / 3
print 9 / 4
print 9 / 4.0
print 9 // 4.0
print 9 % 4
</pre>

<p>
The example demonstrates division operators.
</p>

<pre class="explanation">
print 9 / 4
</pre>

<p>
This results in 2. The division operator works differently for integers and 
for floating point numbers. Integer division gives an integer result. The 
fraction part is truncated. Hence we get:  <code>9 / 4 = 2</code>
</p>

<pre class="explanation">
print 9 / 4.0
</pre>

<p>
Here we get the expected value: 2.25. One of the operands is a floating point 
number, so the result is a floating point too. 
</p>

<pre class="explanation">
print 9 // 4.0
</pre>

<p>
Python has also a special floor division operator. The result is the floor of 
the value returned by true division.
</p>



<pre class="explanation">
print 9 % 4
</pre>

<p>
The <b>%</b> operator is called the modulo operator. It finds the remainder of 
division of one number by another. <code>9 % 4</code>, 9 modulo 4 is 1, because 
4 goes into 9 twice with a remainder of 1. 
</p>


<pre>
$ ./division.py 
3
2
2.25
2.0
1
</pre>

<pre class="code">
>>> 'return' + 'of' + 'the' + 'king'
'returnoftheking'
</pre>

<p>
The addition operator can be used to concatenate strings as well. 
</p>

<pre class="code">
>>> 3 + ' apples'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</pre>

<p>
We cannot add integers and strings. This results in a <code>TypeError</code>. 
</p>

<pre class="code">
>>> str(3) + ' apples'
'3 apples'
</pre>

<p>
For the example to work, we must convert the number to a string using the 
<code>str()</code> function. 
</p>

<p>
On the other hand, the multiplication operator can be used with a string and a number. 
</p>

<pre class="code">
>>> 'dollar ' * 5
'dollar dollar dollar dollar dollar '
</pre>



<h2>Boolean operators</h2>

<p>
In Python, we have <code>and</code>, <code>or</code> and <code>not</code> boolean 
operators. With boolean operators we perform logical operations. These are most often 
used with if and while keywords. 
</p>

<pre class="code">
#!/usr/bin/python

# andop.py

print True and True
print True and False
print False and True
print False and False
</pre>

<p>
This example shows the logical and operator. The logical and operator evaluates 
to True only if both operands are True.
</p>

<pre>
$ ./andop.py 
True
False
False
False
</pre>

<p>
The logical or operator evaluates to True, if either of the operands is True.
</p>

<pre class="code">
#!/usr/bin/python

# orop.py

print True or True
print True or False
print False or True
print False or False
</pre>

<p>
If one of the sides of the operator is True, the outcome of the operation is True. 
</p>

<pre>
$ ./orop.py 
True
True
True
False
</pre>

<p>
The <b>negation</b> operator <code>not</code> makes True False and False True. 
</p>

<pre class="code">
#!/usr/bin/python

# negation.py

print not False
print not True
print not ( 4 &lt; 3 )
</pre>

<p>
The example shows the not operator in action.
</p>

<pre>
$ ./negation.py 
True
False
True
</pre>

<p>
And, or operators are short circuit evaluated. 
<b>Short circuit evaluation</b> means that the second argument is only evaluated 
if the first argument does not suffice to determine the value of the expression: 
when the first argument of and evaluates to false, the overall value must be false; 
and when the first argument of or evaluates to true, the overall value must be true. (wikipedia)
</p>

<p>
A typical example follows. 
</p>

<pre class="code">
#!/usr/bin/python

# shortcircuit.py

x = 10
y = 0

if (y != 0 and x/y &lt; 100):
      print "a small value"
</pre>

<p>
The first part of the expression evaluates to False. The second part of the 
expression is not evaluated. 
Otherwise, we would get a ZeroDivisionError.
</p>


<h2>Relational Operators</h2>

<p>
Relational operators are used to compare values. These operators always 
result in a boolean value. 
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>&lt;</td><td>strictly less than</td></tr>
<tr class="gray"><td>&lt;=</td><td>less than or equal to</td></tr>
<tr><td>&gt;</td><td>greater than</td></tr>
<tr class="gray"><td>&gt;=</td><td>greater than or equal to</td></tr>
<tr><td>==</td><td>equal to</td></tr>
<tr class="gray"><td>!= or &lt;&gt;</td><td>not equal to</td></tr>
<tr><td>is</td><td>object identity</td></tr>
<tr class="gray"><td>is not</td><td>negated object identity</td></tr>
</table>

<p>
The above table shows Python relational operators.
</p>

<pre class="code">
>>> 3 &lt; 4
True
>>> 4 == 3
False
>>> 4 &gt;= 3
True
</pre>

<p>
As we already mentioned, the relational operators return boolean values. True or False.
</p>

<p>
Notice that the relational operators are not limited to numbers. We can use them 
for other objects as well. Although they might not always be meaningful. 
</p>

<pre class="code">
>>> "six" == "six"
True
>>> "a" > 6
True
>>> 'a' &lt; 'b'
True
</pre>

<p>
We can compare string objects too. We can use relational operators for different 
object types. In our case we compare a string with a number. 
</p>

<pre class="explanation">
>>> 'a' &lt; 'b'
</pre>

<p>
What exactly happens here? Computers do not know characters or strings. For them, 
everything is just a number. Characters are special numbers stored in specific 
tables. Like ASCII. 
</p>

<pre class="code">
#!/usr/bin/python

# compare.py


print 'a' &lt; 'b'

print "a is:", ord('a')
print "b is:", ord('b')
</pre>

<p>
Internally, the a and b characters are numbers. So when we compare two characters, 
we compare their stored numbers. The built-in <code>ord()</code> function 
returns the ASCII value of a single character. 
</p>

<pre>
$ ./compare.py 
True
a is: 97
b is: 98
</pre>

<p>
In fact, we compare two numbers. 97 with 98. 
</p>

<pre class="code">
>>> "ab" > "aa"
True
</pre>

<p>
Say we have a string with more characters. If the first characters are equal, we 
compare the next ones. In our case, the b character at the second position has a 
greater value than the a character. That is why "ab" string is greater than "aa" string. 
Comparing strings in such a way does not make much sense, of course. But it is 
technically possible.
</p>

<pre class="code">#!/usr/bin/python

# objects.py

print None == None
print None is None

print True is True

print [] == []
print [] is []

print "Python" is "Python"
</pre>

<p>
The == operator tests for equality The <b>is</b> keyword tests 
for object identity. Whether we are talking about the same object. Note, that more 
variables may refer to the same object. 
</p>

<pre>
$ ./objects.py 
True
True
True
True
False
True
</pre>

<p>
The output might be surprising for you. In Python language, there is only one 
None and one True object. That's why True is equal and also identical to True. 
There is only one truth out there, anyway. The empty list [] is equal to another empty list [].
But they are not identical. Python has put them into two different memory locations. 
They are two distinct objects.  Hence the is keyword returns False. On the other 
hand, "Python" is "Python" returns True. This is because of optimalisation.
If two string literals are equal, they have been put to same memory location. 
A string is an immutable entity. No harm can be done. 
</p>


<h2>Bitwise operators</h2>

<p>
Decimal numbers are natural to humans. Binary numbers are native to comptuters. 
Binary, octal, decimal or hexadecimal symbols are only notations of the same number. 
Bitwise operators work with bits of a binary number. We have binary logical operators 
and shift operators. Bitwise operators are seldom used in higher level languages like Python. 
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>~</td><td>bitwise negation</td></tr>
<tr class="gray"><td>^</td><td>bitwise exclusive or</td></tr>
<tr><td>&amp;</td><td>bitwise and</td></tr>
<tr class="gray"><td>|</td><td>bitwise or</td></tr>
<tr><td>&lt;&lt;</td><td>left shift</td></tr>
<tr class="gray"><td>&gt;&gt;</td><td>right shift</td></tr>
</table>

<p>
The <b>bitwise negation operator</b> changes each 1 to 0 and 0 to 1. 
</p>

<pre class="code">
>>> ~7
-8
>>> ~-8
7
</pre>

<p>
The operator reverts all bits of a number 7. One of the bits also determines, 
whether the number is negative or not. 
If we negate all the bits one more time, we get number 7 again. 
</p>

<p>
The <b>bitwise and operator</b> performs bit-by-bit comparison between two nubmers. 
The result for a bit position is 1 only if both corresponding bits in the operands are 1. 
</p>

<pre>
     00110
  &amp;  00011
   = 00010
</pre>

<p>
The first number is a binary notation of 6. The second is 3. The result is 2. 
</p>

<pre class="code">
>>> 6 &amp; 3
2
>>> 3 &amp; 6
2
</pre>

<p>
The <b>bitwise or operator</b> performs bit-by-bit comparison between two nubmers. 
The result for a bit position is 1 if either of the corresponding bits in the operands is 1. 
</p>

<pre>
     00110
  |  00011
   = 00111
</pre>

<p>
The result is <code>00110</code> or decimal 7. 
</p>

<pre class="code">
>>> 6 | 3
7
</pre>

<p>
The <b>bitwise exclusive or operator</b> performs bit-by-bit comparison 
between two nubmers. The result for a bit position is 1 if one or the other 
(but not both) of the corresponding bits in the operands is 1. 
</p>

<pre>
     00110
  ^  00011
   = 00101
</pre>

<p>
The result is <code>00101</code> or decimal 5. 
</p>

<pre class="code">
>>> 6 ^ 3
5
</pre>

<p>
As we mentioned, bitwise operators are seldom used in Python and other high 
level languages. Yet there are some situations, where they are used. One example 
is a <b>mask</b>. A mask is a specific bit pattern. It determines whether some 
property is set or not.  
</p>

<p>
Let's have an example from GUI programming. 
</p>


<pre class="code">
#!/usr/bin/python

# nominimizebox.py

import wx

app = wx.App()
window = wx.Frame(None, style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER 
	| wx.SYSTEM_MENU | wx.CAPTION |	 wx.CLOSE_BOX)
window.Show(True)

app.MainLoop()
</pre>

<p>
This is a small example of a wxPython code. wx.MAXIMIZE_BOX, wx.RESIZE_BORDER, 
wx.SYSTEM_MENU, wx.CAPTION and wx.CLOSE_BOX are constants. The bitwise or operator 
adds all these constants to the mask. In our case, all these
properties are set using the bitwise or operator and applied to the wx.Frame widget. 
</p>

<p>
Finally, we also have bitwise shift operators. The <b>bitwise shift operators</b> 
shift bits to the right or left. 
</p>

<pre>
number &lt;&lt; n : multiply number 2 to the nth power
number &gt;&gt; n : divide number by 2 to the nth power
</pre>

<p>
These operators are also called arithmetic shift. 
</p>

<pre>
     00110
  >>  00001
   = 00011
</pre>

<p>
We shift each of the bits of number six to the right. It is equal to 
dividing the six by 2. The result is <code>00011</code> or decimal 3. 
</p>

<pre class="code">
>>> 6 &gt;&gt; 1
3
</pre>


<pre>
     00110
  &lt;&lt; 00001
   = 01100
</pre>

<p>
We shift each of the bits of number six to the left. It is equal to 
muliplying the number six by 2. The result is <code>01100</code> or decimal 12. 
</p>

<pre class="code">
>>> 6 &lt;&lt; 1
12
</pre>


<h2>Compound assignment operators</h2>

<p>
The compound assignment operators consist of two operators. They are 
shorthand operators. 
</p>

<pre class="code">
>>> i = 1
>>> i = i + 1
>>> i
2
>>> i += 1
>>> i
3
</pre>

<p>
The += compound operator is one of these shorthand operators. They are less 
readable than the full expressions but experienced programmers often use them. 
</p>

<p>
Other compound operators are: 
</p>

<pre>
-=   *=   /=   //=   %=   **=   &amp;=   |=   ^=   &gt;&gt;=   &lt;&lt;=
</pre>


<h2>Operator precedence</h2>

<p>
The <b>operator precedence</b> tells us which operators are evaluated first. 
The precedence level is necessary to avoid ambiguity in expressions. 
</p>

<p>
What is the outcome of the following expression? 28 or 40?
</p>

<pre>
3 + 5 * 5
</pre>

<p>
Like in mathematics, the multiplication operator has a higher precedence 
than addition operator. So the outcome is 28.
</p>

<pre>
(3 + 5) * 5
</pre>

<p>
To change the order of evaluation, we can use square brackets. Expressions 
inside square brackets are always evaluated first. 
</p>

<p>
The following list shows operator precedence in Python. 
</p>

<pre>
   unary +  -  ~
   **
   *  /  %
   +  -
   &gt;&gt;  &lt;&lt;
   &amp;
   ^
   |
   &lt;  &lt;=  ==  &gt;=  &gt;  !=  &lt;&gt;  is
   not
   and 
   or
</pre>

<p>
The operators on the same row have the same level of precedence. The 
precedence grows from bottom to top.
</p>

<pre class="code">
#!/usr/bin/python

# precedence.py


print 3 + 5 * 5
print (3 + 5) * 5

print 2 ** 3 * 5
print not True or True
print not (True or True)
</pre>

<p>
In this code example, we show some common expressions. The outcome of 
each expression is dependent on the precedence level.
</p>

<pre class="explanation">
print 2 ** 3 * 5
</pre>

<p>
The power operator has higher precedence than the multiplication operator. 
First, the <code>2 ** 3</code> is evaluated, which returns 8. Than the outcome 
is multiplied by 5. <code>8 * 5</code>. And the result is 40. 
</p>

<pre class="explanation">
print not True or True
</pre>

<p>
In this case, the not operator has a higher precedence. First, the first True 
value is negated to False, that the or operator 
combines False and True, which gives True in the end. 
</p>

<pre>
$ ./precedence.py 
28
40
40
True
False
</pre>

<p>
The relational operators have a higher precedence than logical operators. 
</p>

<pre class="code">
#!/usr/bin/python

# positive.py

a = 1
b = 2

if (a > 0 and b > 0):
   print "a and b are positive integers"
</pre>

<p>
The and operator awaits two boolean values. If one of the operands would 
not be a boolean value, we would get a syntax error. In Python, the relational 
operators are evaluated first. The logical operator then. 
</p>

<pre>
$ ./positive.py 
a and b are positive integers
</pre>


<h2>Associativity</h2>

<p>
Sometimes the precedence is not satisfactory to determine the outcome of 
an expression. There is another rule called <b>associativity</b>. The associativity 
of operators determines the order of evaluation of operators with the <b>same</b>
precedence level. 
</p>

<pre>
9 / 3 * 3
</pre>

<p>
What is the outcome of this expression? 9 or 1? The multiplication, deletion 
and the modulo operator are left to right associated. So the expression is 
evaluated this way: <code>(9 / 3) * 3</code> and the result is 9.
</p>

<p>
Arithmetic, boolean, relational and bitwise operators are all left to right associated. 
</p>


<p>
On the other hand, the assignment operator is right associated. 
</p>

<pre class="code">
>>> a = b = c = d = 0
>>> a, b, c, d
(0, 0, 0, 0)
</pre>

<p>
If the association was left to right, the previous expression would not be possible. 
</p>

<p>
The compound assignment operators are right to left associated. 
</p>

<pre class="code">
>>> j = 0
>>> j *= 3 + 1
>>> j
0
</pre>

<p>
You might expect the result to be 1. But the actual result is 0. Because of 
the associativity. The expression on the right is evaluated first and than 
the compound assignment operator is applied.
</p>

<p>
In this chapter, we have talked about operators in Python.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 16, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

